#include "client.h"

int doLogin(int sockfd){
    char username[50]={0};
    char password[50]={0};
    printf("please input username:");
    fflush(stdout);
    int ret=read(STDOUT_FILENO,username,sizeof(username));
    username[--ret]='\0';
    printf("please input password:");
    fflush(stdout);
    ret=read(STDOUT_FILENO,password,sizeof(password));
    password[--ret]='\0';

    // 发送用户名
    commandPacket_t usernameInfo;
    bzero(&usernameInfo,sizeof(usernameInfo));
    usernameInfo.cmd=LOGIN;
    strcpy(usernameInfo.argument,username);
    usernameInfo.length=strlen(username);
    send(sockfd,&usernameInfo,sizeof(usernameInfo.cmd)+
         sizeof(usernameInfo.length)+usernameInfo.length,0);

    // 接收服务器的返回值
    int exist=-1;
    recvn(sockfd,&exist,sizeof(exist));
    // 如果存在,继续执行登录
    if(exist==1){
      // 发送密码加密后得到的密文
      char salt[30]={0};
      recvn(sockfd,&usernameInfo.cmd,sizeof(usernameInfo.cmd));
      recvn(sockfd,&usernameInfo.length,sizeof(usernameInfo.length));
      recvn(sockfd,usernameInfo.argument,usernameInfo.length);
      strcpy(salt,usernameInfo.argument);
      char *cip=crypt(password,salt);
      usernameInfo.cmd=LOGIN;
      usernameInfo.length=strlen(cip);
      strcpy(usernameInfo.argument,cip);
      send(sockfd,&usernameInfo,sizeof(usernameInfo.cmd)+
          sizeof(usernameInfo.length)+usernameInfo.length,0);
      
      // 接收密码是否正确的结果
      int loginStatus=-1;
      recvn(sockfd,&loginStatus,sizeof(loginStatus));
      if(loginStatus==1){
          printf("Login successfully.\n");
          return 0;
      }
      else{
          printf("Login failed.\n");
          return 1;
      }
    }
    // 用户名不存在，登录失败返回
    else{
        printf("Username Not Found.\n");
        return 1;
    }
    return 0;
}




